package com.dartfar.mail.service;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.type.BooleanType;
import org.hibernate.type.IntegerType;
import org.hibernate.type.Type;
import org.springframework.stereotype.Component;

import com.dartfar.base.dao.DaoUtil;
import com.dartfar.mail.model.MailState;

@Component("mailStateService")
public class MailStateServiceImpl implements MailStateService {

	private DaoUtil<MailState> mailStateDaoUtil;
	
	@Override
	public List<MailState> getMailListByUserId(int id) {
		// TODO Auto-generated method stub
		List<MailState> mails = mailStateDaoUtil.getList("from MailState as m where m.receiveUser.id = ? order by m.receiveDate desc",
				 new Object[]{id},new Type[]{new IntegerType()});
		
		System.out.println("fdff: " + mails.size());
		if (mails.isEmpty()) {
			return null;
		} else {
			return mails;
		}
	}

	@Override
	public List<MailState> getReceiveListByUserIdByLimit(int userId, int limit) {
		// TODO Auto-generated method stub
		
		return null;
	}

	@Override
	public Long getMailReceiveCount(int id) {
		// TODO Auto-generated method stub
		return (long) mailStateDaoUtil.getCount(
				"select count(*) from MailState m where m.mail.id = ?",
				new Object[]{id},new Type[]{new IntegerType()});
	}

	@Override
	public void chageMailSate(int id, Boolean flag) {
		// TODO Auto-generated method stub
		MailState ms = mailStateDaoUtil.get(id, MailState.class);
		ms.setReadFlag(flag);
		mailStateDaoUtil.save(ms);
	}

	@Override
	public List<MailState> getMailListBySate(int id, Boolean flag) {
		// TODO Auto-generated method stub
		List<MailState> mails = mailStateDaoUtil.getList(
				"from MailState m where m.receiveUser.id = ? and m.readFlag = ? order by m.receiveDate desc",
				new Object[]{id, flag},new Type[]{new IntegerType(), new BooleanType()});
		if (mails.isEmpty()) {
			return null;
		} else {
			return mails;
		}
	}

	@Override
	public Long getMailCountBySate(int id, Boolean flag) {
		// TODO Auto-generated method stub
		return (long) mailStateDaoUtil.getCount(
				"select count(*)from MailState m where m.receiveUser.id = ? and m.readFlag = ? ",
				new Object[]{id, flag},new Type[]{new IntegerType(), new BooleanType()});
	}

	@Resource
	public void setMailStateDaoUtil(DaoUtil<MailState> mailStateDaoUtil) {
		this.mailStateDaoUtil = mailStateDaoUtil;
	}
	
	

}
